package server;

import java.util.Iterator;

import communication.StillOnlineRequest;

/**
 * <h1>Class IdleThread</h1>
 * 
 * The IdleThread periodically polls the users to check if they are still online.
 * If the user fails to respond to the message, the session will be closed.
 * This thread also writes the Statistics to the database periodically.
 * 
 * @author Tomas
 * @date March 10 2009
 */
public class IdleThread extends Thread{

	/**
	 * Last time we saved the statistics.
	 */
	protected long lastCommit;
	
	/**
	 * Checks if the thread is finished
	 */
	protected boolean finished;
	
	/**
	 * Instance of the server.
	 */
	protected ServerMonitor server = null;
	
	/**
	 * Default constructor. Initializes the thread.
	 */
	public IdleThread(){
		
		lastCommit = System.currentTimeMillis();
		finished = false;
		
	}
	
	/**
	 * Thread main loop.
	 */
	public void run(){
		
		server = ServerMonitor.getInstance();
		
		while(!finished){
			
			try{
				// We will be polling every 5 minutes.
				Thread.sleep(5 * 60 * 1000);
			}catch(Exception e){
				LogException.getInstance().logException(e);
			}
			
			Iterator<String> it = server.getUsersOnline();
			while(it.hasNext()){
				synchronized(it){
					String name = it.next();
					Session s = server.getSession(name);
					if(s != null){
						long last = s.getLastActivity();
						long now = System.currentTimeMillis();
						long timeidle = (now - last)/(60 * 1000);
						if(timeidle > 10){
							server.removeSession(name);
						}else if(timeidle > 4){
							StillOnlineRequest req = new StillOnlineRequest(name);
							s.sendRequest(req);
						}
					}
				}
			}
			
			// TODO: Store stats if necessary
		}
		
	}
	
	/**
	 * Stops the thread.
	 */
	public void finish(){
		
		finished = true;
		
	}
}
